package com.paraz.cst.impl;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.paraz.cst.CstException;
import com.paraz.cst.CstLooper;
import com.paraz.cst.CstProcessor;
import com.paraz.cst.CstProcessorRequest;
import com.paraz.cst.CstProcessorResult;
import com.paraz.cst.CstProcessorResultHandler;
import com.paraz.cst.SyncCstLooper;

/**
 * Main class, sync, with manual dependency setup.
 * 
 * @author mparaz
 *
 */
public class SyncRealCstMain {

	public static void main(String[] args) throws IOException, CstException {
		final int port = Integer.parseInt(args[0]);
		
		// Infinite number of threads.
		final ExecutorService executorService = Executors.newCachedThreadPool();
		
		// Dependency setup
		
		// Create and setup the looper.
		final CstLooper<Object> cstLooper = new SyncCstLooper();
		cstLooper.setCstProcessor(new CstProcessorImpl());
		
		// Create and setup the server.
		final RealCstSocketServer<Object> server = new RealCstSocketServer<Object>();
		server.setCstLooper(cstLooper);
		server.setExecutorService(Executors.newCachedThreadPool());
		server.setPort(port);
		server.setExecutorService(executorService);
		
		// Make the server serve.
		server.serve();
	}

	/**
	 * Synchronous processor.
	 * 
	 * @author mparaz
	 *
	 */
	private static class CstProcessorImpl implements CstProcessor<Object> {

		public CstProcessorResult process(CstProcessorRequest request,
				Object reference, CstProcessorResultHandler<Object> handler) {
			
			// Just convert the request to uppercase.
			return CstProcessorResult.create(request.getRequest().toUpperCase());
		}
		
	}
	
}
